package com.starbaba.utils;

import org.apache.commons.lang3.StringUtils;

import com.base.common.http.HttpClientUtil;
import com.base.common.http.model.HttpResult;
import com.base.common.log.LogService;
import com.google.gson.JsonObject;
import com.starbaba.common.ConfigFile;
import com.starbaba.common.ConfigFileFactory;
import com.starbaba.model.utils.JSONUtils;
import com.starbaba.redis.JedisUtils;
import com.tuanzi.server.loan_base.constant.WeixinRedisKey;

public class WeixinUtils {
	
	private static final String LOGGER_NAME = WeixinUtils.class.getName();
	private static final String CONFIG_FILE_NAME = "weixin_common";
	
	 /**
	  * 根据appID和appsecret获取Token
	  * @param type 产品类型，4代表菠萝贷服务号
	  * @return
	  */
	 public static String getAccessToken(int type) {
	        String redisKey = WeixinRedisKey.WEIXIN_ACCESS_TOKEN + type;
	        String token = JedisUtils.get(redisKey);
	        if (StringUtils.isEmpty(token)) {
	            String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + getAppId(type) + "&secret=" + getAppSecret(type);
	            try {
	                HttpResult result = HttpClientUtil.get(url);
	                String jsonString = new String(result.getData(), "UTF-8");
	                JsonObject resultJson = JSONUtils.toJsonObject(jsonString);
	                token = resultJson.getAsJsonPrimitive("access_token").getAsString();
	                JedisUtils.set(redisKey, token);
	                int expire = resultJson.getAsJsonPrimitive("expires_in").getAsInt();
	                int shortExpire = expire - (60 * 30); // 提前30分钟失效
	                JedisUtils.expire(redisKey, shortExpire > 0 ? shortExpire : expire);
	            } catch (Exception e) {
	                LogService.error(LOGGER_NAME + ": 获取AccessToken异常", e);
	            }
	        }
	        return token;
	  }
	 
	 private static String getAppId(int type) {
	        String redisKey = WeixinRedisKey.WEIXIN_APP_ID + type;
	        String propKey = "app_id_" + type;
	        String appId = JedisUtils.get(redisKey);
	        if (StringUtils.isEmpty(appId)) {
	            appId = getValue(propKey);
	            JedisUtils.set(redisKey, appId);
	        }
	        return appId;
	    }
	 
	 private static String getAppSecret(int type) {
	        String redisKey = WeixinRedisKey.WEIXIN_APP_SECRET + type;
	        String propKey = "app_secret_" + type;
	        String appSecret = JedisUtils.get(redisKey);
	        if (StringUtils.isEmpty(appSecret)) {
	            appSecret = getValue(propKey);
	            JedisUtils.set(redisKey, appSecret);
	        }
	        return appSecret;
	    }
	 
	 private static String getValue(String key) {
	        ConfigFile properties = ConfigFileFactory.getInstance().get(CONFIG_FILE_NAME);
	        return properties.getValue(key);
	    }

}
